package com.librarySys.librarySys.Controller;


import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.librarySys.librarySys.Bean.*;
import com.librarySys.librarySys.Mapper.CommonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.librarySys.librarySys.myUtil.*;

import java.security.Principal;
import java.util.*;

@Controller
public class CommonController {

    @Autowired
    CommonMapper commonMapper;

    @ResponseBody
    @RequestMapping("test")
    public List<Authority> test(){
        return commonMapper.getAllAuthority();
    }

    @GetMapping("register")
    public String getRegister(){
        return "register";
    }

    @ResponseBody
    @RequestMapping("registerUsernameCheck/{username}")
    public String checkUserExistance(@PathVariable("username")String username){
        if (commonMapper.getUserByUserName(username)!=null){
            return "no";
        }
        return "yes";
    }


    @GetMapping("login")
    public String getLogin(){
        return "login";
    }

    @ResponseBody
    @PostMapping("login")
    public String setLogin(@RequestParam("username")String username,@RequestParam("password")String password){
        User user;
        try {
            user = commonMapper.getUserByUserName(username);
            if (user.getPassword().equals(password)){
                return "登陆成功！";
            }
            else return "密码错误！";
        }catch (Exception e){
            System.out.println("Error:"+e);
            return "没有这个用户！";
        }
    }

    @PostMapping("register")
    public String setRegister(User user){ ;
        user.setRoleId(1);
        System.out.println("注册："+user.getUsername());
        user.setPassword(new iPasswordEncoder().encode(user.getPassword()));
        commonMapper.insertUser(user);
        return "login";
    }

    @GetMapping("manager/addBookType")
    public String getAddBookType(){
        return "libSysManager/addBookType";
    }

    @GetMapping("manager/editBookType/{bookTypeId}")
    public String getEditBookType(@PathVariable("bookTypeId")Integer bookTypeId, Model model){
        model.addAttribute("bookTypeId",bookTypeId);
        model.addAttribute("bookTypeInfo",commonMapper.getBookTypeByBookTypeId(bookTypeId));
        return "libSysManager/editBookType";
    }



    @ResponseBody
    @PostMapping("manager/editBookType/{bookTypeId}")
    public String setEditBookType(@PathVariable("bookTypeId")Integer bookTypeId,BookType bookType){
        try {
            bookType.setBookTypeId(bookTypeId);
            commonMapper.updateBookType(bookType);
            return "修改完成";
        }catch (Exception e){
            System.out.println("Error:"+e);
            return "修改失败";
        }
    }


    @PostMapping("manager/addBookType")
    public String setAddBookType(BookType bookType){
        System.out.println("新增分类！"+bookType.getTitle());
        try {
            commonMapper.insertBookType(bookType);
        }catch (Exception e){
            System.out.println("Error:"+e);
        }
        return "redirect:/manager/addBookType";
    }



    @ResponseBody
    @RequestMapping("manager/addBook/{id}")
    public String addBook(@PathVariable("id") Integer id){
        try {
            int res = commonMapper.insertBook(id);
            return "新增书籍成功，代号为："+res;
        }catch (Exception e){
            System.out.println("Error:"+e);
            return "出现错误，新增失败！";
        }
    }

    @ResponseBody
    @RequestMapping("manager/getBookBy/{id}")
    public List<Book> getBookBy(@PathVariable("id") Integer id){
        try {
            return commonMapper.getBookByBookTypeId(id);
        }catch (Exception e){
            System.out.println("Error:"+e);
            return null;
        }
    }

    @ResponseBody
    @RequestMapping("data/getBookSet")
    public List<BookSet> getBookSet(){
        return commonMapper.getAllBookSet();
    }

    @ResponseBody
    @RequestMapping("data/getAuthority/{userId}")
    public List<Authority> getAuthorityById(@PathVariable("userId") Integer userId){
        try{
            List<Authority> res = commonMapper.getAuthorityByUserId(userId);
            System.out.println(res.size());
            return res;
        }catch (Exception e){
            System.out.println("Error:"+e);
            return null;
        }
    }



    @GetMapping({"bookList","/"})
    public String getBookList(Model model){
        model.addAttribute("bookList",commonMapper.getAllBookSet());
        return "libSys/bookList";
    }

    @PostMapping({"bookList"})
    public String getBookListByOrder(Model model){
        model.addAttribute("bookList",commonMapper.getAllBookSetByOrder());
        return "libSys/bookList";
    }

    @PostMapping({"search"})
    public String getBookListBySearch(Model model,@RequestParam("searchText")String searchText){
        System.out.println(searchText);
        model.addAttribute("bookList",commonMapper.getAllBookSetBySearch("%"+searchText+"%"));
        return "libSys/bookList";
    }


    @GetMapping("record")
    public String getRecord(Model model, Authentication authentication){
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))){
            model.addAttribute("record",commonMapper.getAllBorrowRecordInfo());
        }else {
            String username = authentication.getName();
            model.addAttribute("record",commonMapper.getBorrowRecordInfoByUserName(username));
        }
        return "libSys/record";
    }

    @GetMapping("bookList/{bookTypeId}")
    public String getBookListByType(@PathVariable("bookTypeId")Integer bookTypeId,Model model){
        model.addAttribute("bookList",commonMapper.getBookByBookTypeId(bookTypeId));
        model.addAttribute("bookTypeId",bookTypeId);
        return "libSys/bookListByType";
    }


    @ResponseBody
    @PostMapping("manager/deleteBook/{id}")
    public String deleteBook(@PathVariable("id") Integer bookId){
        try {
            System.out.println("Delete:"+bookId);
            commonMapper.deleteBookById(bookId);
            return "已经删除";
        }catch (Exception e){
            return "无法删除";
        }
    }

    @ResponseBody
    @PostMapping("manager/deleteBookType/{id}")
    public String deleteBookType(@PathVariable("id") Integer bookTypeId){
        try {
            commonMapper.deleteBookTypeById(bookTypeId);
            System.out.println("Delete:"+bookTypeId);
            return "已经删除";
        }catch (Exception e){
            return "无法删除";
        }
    }




    // 借书
    @ResponseBody
    @PostMapping("manager/borrowBook/{bookId}/{userId}")
    public String borrow(@PathVariable("bookId")Integer bookId, @PathVariable("userId")Integer userId){
        try {
            System.out.println(bookId+" : "+userId);
            commonMapper.updateBookStateByBookId(bookId);
            BookRecord thisBookRecord = new BookRecord();
            thisBookRecord.setBookId(bookId);
            thisBookRecord.setBorrowTime(new Date());
            thisBookRecord.setState(1);
            thisBookRecord.setUserId(userId);
            commonMapper.insertBorrowRecord(thisBookRecord);
            return "已经添加";
        }catch (Exception e){
            return "无法添加";
        }
    }

    @ResponseBody
    @PostMapping("manager/returnBook/{bookId}")
    public String returnBorrowedBookByBookId(@PathVariable("bookId")Integer bookId){
        try {
            commonMapper.updateReturnBookStateByBookId(bookId);
            commonMapper.updateBorrowRecordByBookId(bookId);
            return "已经添加";
        }catch (Exception e){
            return "无法添加";
        }
    }

    @ResponseBody
    @GetMapping("test/borrow/{bookId}/{userId}")
    public List<BookRecord> testBorrow(@PathVariable("bookId")Integer bookId,@PathVariable("userId")Integer userId){
        BookRecord thisB = new BookRecord();
        thisB.setUserId(userId);
        thisB.setState(1);
        thisB.setBorrowTime(new Date());
        thisB.setBookId(bookId);
        commonMapper.insertBorrowRecord(thisB);
        return commonMapper.getAllBorrowRecord();
    }

    @GetMapping("manager/userList")
    public String getUserList(){
        return "libSysManager/userList";
    }

    @ResponseBody
    @GetMapping("manager/getUserList")
    public HashMap getUserListData(){
        HashMap<String,Object> res = new HashMap<>();
        res.put("code","0");
        res.put("data",commonMapper.getAllUser());
        return res;
    }

    @GetMapping("user/userInfo")
    public String getUserInfo(Principal principal,Model model){
        String userName=principal.getName();
        User user = commonMapper.getUserByUserName(userName);
        model.addAttribute("userData",user);
        return "libSys/userInfo";
    }

    @ResponseBody
    @GetMapping("manager/userSearch/{keyword}")
    public HashMap searchUserInfo(@PathVariable("keyword")String keyword){
        HashMap<String,Object> res = new HashMap<>();
        res.put("code","0");

        res.put("data",commonMapper.getUserBySearch("%"+keyword+"%"));
        return res;
    }

    @GetMapping("user/pswEdit")
    public String getPswEdit(){
        return "libSys/pswEdit";
    }

    @ResponseBody
    @PostMapping("user/pswEdit")
    public String postPswEdit(Principal principal,String newPassword){
        try{
            String username = principal.getName();
            User user = commonMapper.getUserByUserName(username);
            String passwordGo = new iPasswordEncoder().encode(newPassword);
            commonMapper.updateUserPassword(passwordGo,user.getUserId());
            System.out.println(newPassword);
            return "修改成功！";
        }catch (Exception e){
            System.out.println("Error:/user/pswEdit"+e);
        }
        return "修改失败！";

    }


    @ResponseBody
    @PostMapping("user/pwdChange/{userId}/{password}")
    public String getPswEdit(@PathVariable("userId")Integer userId,@PathVariable("password")String password){
        try {
            System.out.println(userId+":"+password);
            String passRes = new iPasswordEncoder().encode(password);
            commonMapper.updateUserPassword(passRes,userId);
            return "yes";
        }catch (Exception e){
            System.out.println("Error:commonController:/user/pwdChange/{userId}/{password}/error"+password+" "+userId+e);
        }
        return "no";
    }

    @GetMapping("user/userEdit")
    public String getUserEdit(Model model,Principal principal){
        User user = commonMapper.getUserByUserName(principal.getName());
        model.addAttribute("userData",user);
        return "libSys/userEdit";
    }

    @ResponseBody
    @PostMapping("user/userDelete/{userId}")
    public String postUserDelete(@PathVariable("userId")Integer userId){
        try {
            commonMapper.deleteUserByUserId(userId);
            return "yes";
        }catch (Exception e){
            System.out.println("Error:CommonController:/user/userDelete/"+userId+"/error:"+e);
            return "no";
        }
    }

    @GetMapping("user/userManagerEdit/{userId}")
    public String getUserEdit(@PathVariable("userId")Integer userId, Model model){
        User user = commonMapper.getUserByUserId(userId);
        model.addAttribute("userData",user);
        return "libSys/userEdit";
    }

    @PostMapping("user/userEditPost")
    public String editUserPost(User user){
        try {
            System.out.println("editUser:"+user.getUserId());
            commonMapper.updateUserByUserId(user);
            return "redirect:/user/userInfo";
        }catch (Exception e){
            System.out.println("Error:commonController:/user/userEditPost"+e);
        }
        return "redirect:/user/userEdit";
    }

    @GetMapping("manager/updateAuth/{userId}")
    public String getUpdateAuth(@PathVariable("userId")Integer userId,Model model){
        model.addAttribute("userId",userId);
        model.addAttribute("auths",commonMapper.getAllRole());
        return "libSysManager/updateAuth";
    }

    @ResponseBody
    @PostMapping("manager/updateAuth/{userId}")
    public String postUpdateAuth(@PathVariable("userId") Integer userFormId, Integer roleId){
        if (roleId==null){
            return "角色不能为空！";
        }
        try {
            System.out.println("updateAuth"+roleId+":"+userFormId);
            commonMapper.updateUserRole(roleId, userFormId);
            return "修改成功";
        }catch (Exception e){
            System.out.println("commonController:post:manager/updateAuth/{userId}/"+userFormId+"/error"+e);
        }
        return "修改失败";
    }
}
